package com.aube.plugin.rank;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.plugin.rank.model.CategoryImp;
import com.aube.plugin.rank.model.CategoryListModel;
import com.aube.plugin.rank.model.CharacterGenerator;
import com.aube.plugin.rank.model.CharacterProxy;
import com.aube.plugin.rank.model.RankAppShare;
import com.aube.plugin.rank.model.RankModel;
import com.aube.plugin.rank.view.FixedSizeImageView;
import com.aube.plugin.rank.view.PagerSlidingTabStrip;
import com.aube.plugin.rank.view.ParallaxRankTopLayout;
import com.aube.plugin.rank.view.ViewPagerRank;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.BlurViewDecorator;
import com.huyn.baseframework.dynamicload.DynamicLoaderHelper;
import com.huyn.baseframework.dynamicload.PluginPackageManager;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.CategorySimple;
import com.huyn.baseframework.model.Character;
import com.huyn.baseframework.share.ShareModule;
import com.huyn.baseframework.share.ShareType;
import com.huyn.baseframework.statesync.IDataObserver;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.ryg.dynamicload.DLBasePluginFragmentActivity;
import com.ryg.dynamicload.internal.DLIntent;
import com.ryg.dynamicload.internal.DLPluginPackage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by huyaonan on 16/8/9.
 */
public class WeekRankActivity extends DLBasePluginFragmentActivity {

    public static final String INTENT_CATEGORY = "INTENT_CATEGORY";
    public static final String INTENT_COLOR = "INTENT_COLOR";
    public static final String INTENT_IDS = "INTENT_IDS";

    private View mRootView;

    private ImageView mBlurBg, mHeadImg;
    private BlurViewDecorator mBlurView;
    private ViewPager mRankVP;

    private ImageView mShareWeiboImg, mShareWechatImg, mShareTimelineImg;
    private View mShareLayout, mShareWeibo, mShareWechat, mShareTimeline;

    private View mBlurLayout;
    private LinearLayout mRankContent;

    private ScrollView mScrollView;
    private ParallaxRankTopLayout mTop;

    private FixedSizeImageView mBottomImage;

    private LinearLayout mHeadLayout;

    private boolean mContentInited = false;

    private CategorySimple mCate;

    private RankViewAdpater mAdapter;

    private boolean mBgInited = false;

    private String[] mRankIds;
    private int mColor;
    private String mModuleCode;

    private RankAppShare mShareData;

    private HashMap<String, RankModel> mRankData = new HashMap<>();

    private int mLastScrollY=0;
    private int targetHeight=0;
    private int statusHeight = 0;
    private int topbarheight = 200;
    private boolean headFilled = false;

    private RankShareHelper mShareHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mCate = (CategorySimple) getIntent().getSerializableExtra(INTENT_CATEGORY);
        mColor = getIntent().getIntExtra(INTENT_COLOR, 0xffffffff);
        mRankIds = getIntent().getStringArrayExtra(INTENT_IDS);

        if(mCate == null) {
            finish();
            return;
        }

        setContentView(R.layout.layout_rank);

        mRootView = findViewById(R.id.rank_rootview);

        mTop = (ParallaxRankTopLayout) findViewById(R.id.rank_parallax_top);
        mTop.setIndicatorColor(mColor);
        mHeadLayout = (LinearLayout) findViewById(R.id.rank_scroll_header);

        mBlurBg = (ImageView) findViewById(R.id.blur_bg);
        mHeadImg = (ImageView) findViewById(R.id.rank_head_img);

        mScrollView = (ScrollView) findViewById(R.id.scrollview);
        
        mBlurLayout = findViewById(R.id.blur_layout);

        mRankVP = (ViewPager) findViewById(R.id.rank_viewpager);

        mRankContent = (LinearLayout) findViewById(R.id.rank_content);

        mBottomImage = (FixedSizeImageView) findViewById(R.id.bottom_img);

        try {
            mBlurView = getBlurView(false);
            mBlurView.setOverlayColor(0xcc202020);
            mBlurView.setBlurredView(mBlurLayout);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mRankContent.addView(mBlurView, 0);

        mShareWeibo = findViewById(R.id.share_weibo);
        mShareWechat = findViewById(R.id.share_wechat);
        mShareTimeline = findViewById(R.id.share_timeline);

        mShareLayout = findViewById(R.id.share_layout);

        mShareWeiboImg = (ImageView) findViewById(R.id.share_weibo_img);
        mShareWechatImg = (ImageView) findViewById(R.id.share_wechat_img);
        mShareTimelineImg = (ImageView) findViewById(R.id.share_timeline_img);

        targetHeight = getResources().getDimensionPixelSize(R.dimen.category_list_head_height);
        statusHeight = SysUtil.getStatusHeight(this);
        topbarheight = getResources().getDimensionPixelOffset(R.dimen.actionbar_height);

        mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                int y = mScrollView.getScrollY();
                if (y == mLastScrollY)
                    return;
                mLastScrollY = y;

                int targetY = targetHeight - y;
                mBlurView.setTranslationY(targetY < 0 ? 0 : targetY);
                mBlurView.invalidate();

                if (y >= targetHeight - topbarheight - statusHeight) {
                    mTop.updateTitleOffset(targetHeight - topbarheight - statusHeight);
                    mTop.updateTitleAlpha(0f);
                } else {
                    mTop.updateTitleOffset(y);
                    float alpha = y*1f/(targetHeight - topbarheight - statusHeight)*2;
                    mTop.updateTitleAlpha(alpha < 1 ? 1-alpha : 0f);
                }
            }
        });

        mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int height = mTop.getIndicatorHeight();
                if(height > 0 && !headFilled) {
                    mHeadLayout.removeAllViews();
                    View header = new View(that);
                    mHeadLayout.addView(header, 0, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, targetHeight-topbarheight-statusHeight));
                    headFilled = true;

                    mScrollView.setPadding(0, topbarheight+statusHeight+height, 0, 0);
                }
            }
        });

        mBlurView.setTranslationY(targetHeight);
    }

    @Override
    public void onResume() {
        super.onResume();

        if(mContentInited)
            return;

        mBlurBg.setImageResource(R.drawable.bk_default);
        mHeadImg.setImageResource(R.drawable.bk_default);
        mBlurView.invalidate();

        mShareLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manageShareLayout(false);
            }
        });

        mShareTimeline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toShare(ShareType.TIMELINE);
            }
        });

        mShareWeibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toShare(ShareType.WEIBO);
            }
        });

        mShareWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toShare(ShareType.WECHAT);
            }
        });

        mShareWeiboImg.setImageResource(R.drawable.icon_weibo);
        mShareWechatImg.setImageResource(R.drawable.icon_wechat);
        mShareTimelineImg.setImageResource(R.drawable.icon_pyq);

        mTop.setOnParallaxTopEventListener(new OnParallaxTopEventListener() {
            @Override
            public void onBackPressed() {
                finish();
            }

            @Override
            public void onShare() {
                if(mShareData == null)
                    return;
                manageShareLayout(true);
            }

            @Override
            public void onRefresh() {
                int index = mRankVP.getCurrentItem();
                if(mRankIds == null || index >= mRankIds.length) {
                    mTop.endLoading();
                    return;
                }
                getDataByTitles(mRankIds[index], true);
            }
        });

        getData();

        mContentInited = true;
    }

    /**
     * 模块内容接口
     * templateCode(index | actor)
     * ostype(iphone|android)
     * modelCode（template接口中获取）
     * relatedId（有就传，比如嘉宾）
     * lastId（分页用，第一次可不传，当前页最后一个id）
     * maxnum（一页最大条数）
     */
    public void getData() {
        HashMap<String, String> params = new HashMap<>();
        params.put(Constant.API_REQUEST_METHOD, "com.aube.app.model.data");
        params.put("templateCode", mCate.templateType);
        params.put("modelCode", mCate.modelCode);
        params.put("relatedId", mCate.relatedId);
        params.put("maxnum", "100");
        params.put("subModelCode", mCate.subModelCode);

        exeHttpRequest(params, CategoryListModel.class, null, new Response.Listener<CategoryListModel>() {
            @Override
            public void onResponse(CategoryListModel response) {
                if(response == null || !response.success())
                    return;
                setupData(response);
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });
    }

    /**
     * 自动加载后页数据或者强制刷新
     * @param weeks
     */
    public void getDataByTitles(String weeks, boolean update) {
        if(mRankVP == null || mAdapter == null)
            return;

        final int index = update ? mRankVP.getCurrentItem() : -1;

        try {
            findViewFromObject(index).refresh(mAdapter.getRankModelByIndex(index), new OnRefreshEndListener() {

                @Override
                public void endLoading() {
                    mTop.endLoading();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            mTop.endLoading();
        }
    }

    private void setupData(CategoryListModel model) {
        if(model.data == null) {
            return;
        }
        for(final CategoryImp category : model.data) {
            if("modelHead".equalsIgnoreCase(category.modelCode)) {
                if(!mBgInited) {
                    ImageLoader.getInstance(that).preloadBitmap(category.headPic.picurl, new ImageLoader.IPreloadCallback<Bitmap>() {
                        @Override
                        public void onSuccess(Bitmap bitmap) {
                            if(bitmap != null) {
                                mBgInited = true;
                                mHeadImg.setImageBitmap(bitmap);
                                mBlurBg.setImageBitmap(bitmap);
                                mBlurView.invalidateSelf();
                            }
                        }

                        @Override
                        public void onFail() {

                        }
                    });
                }
            } else {
                mModuleCode = category.modelCode;

                mTop.setText(category.modelName);
                updateRankDes(category);
                RankNumManager.registRankPageObserver(new IDataObserver() {
                    @Override
                    public void stateUpdate() {
                        updateRankDes(category);
                    }
                });

                final Object strRule = category.getStrFromExtra("ruleUrl");
                if(strRule != null) {
                    mTop.setRuleClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putString("WEB_URL", (String) strRule);
                            startHostActivity("com.aube.activity.WapActivity", bundle);
                        }
                    });
                }

                if(mShareData == null) {
                    mShareData = RankAppShare.setupShareData(category);

                    if(StringUtils.isNotBlank(mShareData.shareLogoUrl)) {
                        mBottomImage.setVisibility(View.VISIBLE);
                        mBottomImage.updateSize(mShareData.width, mShareData.height);
                        mBottomImage.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if(mShareData == null)
                                    return;
                                manageShareLayout(true);
                            }
                        });
                        ImageLoader.getInstance(that).fillImage(mBottomImage, mShareData.shareLogoUrl);
                    }

                    mShareHelper = new RankShareHelper(that, mShareData, new RankShareHelper.IShareBitmapListener() {
                        @Override
                        public void onResponse(int type, String path) {
                            doShare(getShareModule(type, path));
                        }
                    });

                    mShareHelper.preloadImg();
                }

                List<Object> contents = category.dataDetail;
                List<String> keys = new ArrayList<>();
                final String[] titles = new String[contents.size()];
                final int[] imgRes = new int[contents.size()];
                int i=0;
                mRankIds = new String[contents.size()];
                for(Object obj : contents) {
                    RankModel rankModel = CharacterGenerator.generatorRankModel(obj);

                    Object str = category.getStrFromExtra("actorIds");
                    if(str != null)
                        rankModel.actorIds = (String) str;

                    String key = rankModel.getGroupKey();
                    mRankData.put(key, rankModel);

                    keys.add(key);

                    titles[i] = rankModel.desc;
                    if(i == 0)
                        imgRes[0] = R.drawable.icon_ranktotal;
                    else if(i == 1)
                        imgRes[1] = R.drawable.icon_rankweek;

                    mRankIds[i] = rankModel.week;
                    i++;
                }

                if(mAdapter == null) {
                    mAdapter = new RankViewAdpater(keys);
                    mRankVP.setAdapter(mAdapter);
                    mRankVP.setOffscreenPageLimit(contents.size());

                    headFilled = false;
                    mTop.setViewPager(mRankVP, new PagerSlidingTabStrip.IconAndTextTabProvider() {
                        @Override
                        public int[] getPageIconRes() {
                            return imgRes;
                        }

                        @Override
                        public String[] getPageText() {
                            return titles;
                        }

                        @Override
                        public Bitmap getBitmap(int res) {
                            return BitmapFactory.decodeResource(getDLPluginPackage().resources, res);
                        }
                    });
                } else {
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void updateRankDes(Category category) {
        int count = RankNumManager.getLeftChance();
        if(count > 0) {
            Object strDes = category.getStrFromExtra("extraDescAndroid");
            if(strDes != null) {
                String str = (String) strDes;
                if(StringUtils.isNotBlank(str)) {
                    if(str.contains("***"))
                        str = str.replace("***", count+"");
                    mTop.updateDes(str);
                }
            }
        } else {
            Object strDes = category.getStrFromExtra("noChanceVoteDescAndroid");
            if (strDes != null) {
                String str = (String) strDes;
                mTop.updateDes(str);
            }
        }
    }

    /**
     * 组装分享
     */
    private ShareModule getShareModule(int type, String bitmap) {
        if(mShareData == null)
            return null;

        final ShareModule shareModule = new ShareModule();
        shareModule.mShareChannel = type;
        shareModule.shareUrl = mShareData.url;
        if(type == ShareType.WEIBO) {
            shareModule.title = mShareData.weiboTitle;
            shareModule.content = mShareData.weiboTitle;
        } else {
            shareModule.title = mShareData.title;
            shareModule.content = mShareData.content;
        }
        //图片大小不能超过32kb
        shareModule.imagePath = bitmap;
        return shareModule;
    }

    private void manageShareLayout(final boolean show) {
        ValueAnimator anim = ValueAnimator.ofFloat(show ? 0 : 1, show ? 1 : 0);
        anim.setDuration(400);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();

                mShareLayout.setAlpha(value);
                mShareWechat.setAlpha(value);
                mShareWeibo.setAlpha(value);
                mShareTimeline.setAlpha(value);

                if(show) {
                    float translationY = mShareWechat.getHeight() * (1-value);
                    mShareWechat.setTranslationY(translationY);
                    mShareWeibo.setTranslationY(translationY);
                    mShareTimeline.setTranslationY(translationY);
                }
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if(!show) {
                    mShareLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                if(show) {
                    mShareLayout.setAlpha(0f);
                    mShareWechat.setAlpha(0f);
                    mShareWeibo.setAlpha(0f);
                    mShareTimeline.setAlpha(0f);
                    mShareLayout.setVisibility(View.VISIBLE);
                }
            }
        });
        anim.start();
    }

    private DLPluginPackage getDLPluginPackage() {
        if(mPluginPackage != null)
            return mPluginPackage;
        return PluginPackageManager.getInstance().getModule(mModuleCode);
    }

    private ILoginChecker iLoginChecker = new ILoginChecker() {
        @Override
        public boolean isLogin() {
            if(isUserLogin())
                return true;
            return false;
        }

        @Override
        public void exeProxyHttpRequest(HashMap<String, String> params, Class clazz, String tag, Response.Listener listener) {
            exeHttpRequest(params, clazz, tag, listener);
        }

        @Override
        public void onClickToCharacter(Character character) {
            if(character == null)
                return;
//            Bundle bundle = new Bundle();
//            bundle.putSerializable("ACTOR", (character instanceof CharacterProxy) ? ((CharacterProxy) character).toCharacter() : character);
//            startHostActivity("com.aube.activity.CharacterActivity", bundle);
            DLIntent intent = new DLIntent("com.aube.plugin.origin", "com.aube.plugin.figure.CharacterActivity");
            intent.putExtra("ACTOR", (character instanceof CharacterProxy) ? ((CharacterProxy) character).toCharacter() : character);
            startPluginActivity(intent);
        }
    };

    protected class RankViewAdpater extends PagerAdapter {

        private List<String> keys;

        public RankViewAdpater(List<String> keys) {
            this.keys = keys;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            RankModel data = getRankModelByIndex(position);

            ViewPagerRank view = (ViewPagerRank) DynamicLoaderHelper.loadTargetLayout(that, getDLPluginPackage(), ViewPagerRank.class.getName());
            setObjectForPosition(view, position);
            container.addView(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

            view.setLoginChecker(iLoginChecker);
            view.fillData(data);

            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object obj) {
            container.removeView(findViewFromObject(position));
        }

        @Override
        public int getCount() {
            return keys == null ? 0 : keys.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        public String getKeyByIndex(int index) {
            if(keys == null || index < 0 || index >= keys.size())
                return null;
            return keys.get(index);
        }

        public RankModel getRankModelByIndex(int index) {
            if(mRankData == null)
                return null;
            return mRankData.get(getKeyByIndex(index));
        }

    }

    private HashMap<Integer, ViewPagerRank> mObjs = new LinkedHashMap<>();
    public void setObjectForPosition(ViewPagerRank obj, int position) {
        mObjs.put(Integer.valueOf(position), obj);
    }
    public ViewPagerRank findViewFromObject(int position) {
        Object o = mObjs.get(Integer.valueOf(position));
        if (o == null) {
            return null;
        }
        View v;
        for (int i = 0; i < mRankVP.getChildCount(); i++) {
            v = mRankVP.getChildAt(i);
            if (mAdapter.isViewFromObject(v, o))
                return (ViewPagerRank) v;
        }
        return null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            if(mShareLayout != null && mShareLayout.getVisibility() == View.VISIBLE) {
                manageShareLayout(false);
                return true;
            }

            RankNumManager.unregistRankPageObserver();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public View getRootView() {
        return mRootView;
    }

    private void toShare(final int type) {
        manageShareLayout(false);

        if(mShareHelper != null)
            mShareHelper.toShare(type);
    }

}
